<template>
  <div class="table-box">
    <!-- 搜索表单 -->
    <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
      <el-form-item label="工位编码" prop="workstationCode">
        <el-input v-model="searchForm.workstationCode" placeholder="请输入工位编码" clearable style="width: 180px;" />
      </el-form-item>
      <el-form-item label="工位名称" prop="workstationName">
        <el-input v-model="searchForm.workstationName" placeholder="请输入工位名称" clearable style="width: 180px;" />
      </el-form-item>
      <el-form-item label="所属产线" prop="productionLineId">
        <el-select v-model="searchForm.productionLineId" placeholder="请选择产线" clearable style="width: 180px">
          <el-option
            v-for="line in productionLineOptions"
            :key="line.id"
            :label="line.lineName"
            :value="line.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工位类型" prop="workstationType">
        <el-select v-model="searchForm.workstationType" placeholder="请选择类型" clearable style="width: 120px;">
          <el-option label="手动" value="MANUAL" />
          <el-option label="自动" value="AUTOMATIC" />
          <el-option label="半自动" value="SEMI_AUTOMATIC" />
        </el-select>
      </el-form-item>
      <el-form-item label="工位状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px;">
          <el-option label="空闲" value="IDLE" />
          <el-option label="运行中" value="RUNNING" />
          <el-option label="故障" value="FAULT" />
          <el-option label="维护中" value="MAINTENANCE" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-header">
      <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增工位</el-button>
      <el-button type="danger" :icon="Delete" plain :disabled="selectedRows.length === 0" @click="handleBatchDelete">
        批量删除
      </el-button>
    </div>

    <el-table :data="tableData" style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="workstationCode" label="工位编码" width="120" />
      <el-table-column prop="workstationName" label="工位名称" width="120" />
      <el-table-column prop="productionLineName" label="所属产线" width="120" />
      <el-table-column prop="workshopName" label="所属车间" width="120" />
      <el-table-column prop="factoryName" label="所属工厂" width="120" />
      <el-table-column prop="workstationType" label="工位类型" width="100">
        <template #default="scope">
          <el-tag :type="getTypeColor(scope.row.workstationType)">{{ getTypeText(scope.row.workstationType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="capacity" label="产能/小时" width="100" />
      <el-table-column prop="position" label="位置序号" width="100" />
      <el-table-column prop="location" label="位置" width="200" show-overflow-tooltip />
      <el-table-column prop="supportedProcessTypes" label="支持工艺类型" width="150" show-overflow-tooltip>
        <template #default="scope">
          <span v-if="scope.row.supportedProcessTypes">{{ scope.row.supportedProcessTypes }}</span>
          <span v-else class="text-gray-400">-</span>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" min-width="120" show-overflow-tooltip />
      <el-table-column label="操作" min-width="200" fixed="right">
        <template #default="scope">
          <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
          <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
          <el-button type="danger" link :icon="Delete" @click="deleteWorkstation(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>

    <WorkstationDrawer ref="drawerRef" />
  </div>
</template>

<script setup lang="ts" name="workstationManage">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, EditPen, View, Delete } from "@element-plus/icons-vue";
import WorkstationDrawer from "./form.vue";
import {
  getWorkstationList,
  createWorkstation,
  updateWorkstation,
  deleteWorkstation as deleteWorkstationApi,
  batchDeleteWorkstation,
  getEnabledProductionLineList,
  type Workstation
} from "@/api/modules/workstation";

const loading = ref(false);
const tableData = ref<Workstation.WorkstationListItem[]>([]);
const selectedRows = ref<Workstation.WorkstationListItem[]>([]);
const searchFormRef = ref<FormInstance>();
const productionLineOptions = ref<{ id: string; lineName: string }[]>([]);

// 查询表单
const searchForm = reactive({
  workstationCode: "",
  workstationName: "",
  productionLineId: undefined as string | undefined,
  workstationType: "",
  status: ""
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm,
      current: pagination.currentPage,
      size: pagination.pageSize
    };
    const res = await getWorkstationList(params);
    tableData.value = res.data.records;
    pagination.total = res.data.total;
  } catch (error) {
    ElMessage.error("获取工位列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取产线选项
const loadProductionLineOptions = async () => {
  try {
    const res = await getEnabledProductionLineList();
    productionLineOptions.value = res.data || [];
  } catch (error) {
    console.error("获取产线列表失败:", error);
  }
};

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    IDLE: "info",
    RUNNING: "success",
    FAULT: "danger",
    MAINTENANCE: "warning"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    IDLE: "空闲",
    RUNNING: "运行中",
    FAULT: "故障",
    MAINTENANCE: "维护中"
  };
  return statusMap[status] || status;
};

// 获取类型颜色
const getTypeColor = (type: string) => {
  const typeMap: Record<string, string> = {
    MANUAL: "primary",
    AUTOMATIC: "success",
    SEMI_AUTOMATIC: "warning"
  };
  return typeMap[type] || "info";
};

// 获取类型文本
const getTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    MANUAL: "手动",
    AUTOMATIC: "自动",
    SEMI_AUTOMATIC: "半自动"
  };
  return typeMap[type] || type;
};

// 表格选择项变化
const handleSelectionChange = (rows: Workstation.WorkstationListItem[]) => {
  selectedRows.value = rows;
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) return;

  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条工位吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      const ids = selectedRows.value.map(row => row.id);
      await batchDeleteWorkstation(ids);
      ElMessage.success("批量删除成功");
      getTableData();
    } catch (error) {
      ElMessage.error("批量删除失败");
    }
  });
};

// 查询
const handleSearch = () => {
  pagination.currentPage = 1;
  getTableData();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    workstationCode: "",
    workstationName: "",
    productionLineId: undefined,
    workstationType: "",
    status: ""
  });
  pagination.currentPage = 1;
  getTableData();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  getTableData();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  getTableData();
};

// 删除工位
const deleteWorkstation = async (row: Workstation.WorkstationListItem) => {
  ElMessageBox.confirm(`确认删除工位 "${row.workstationName}" 吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      await deleteWorkstationApi(row.id);
      ElMessage.success(`删除工位【${row.workstationName}】成功`);
      getTableData();
    } catch (error) {
      ElMessage.error("删除工位失败");
    }
  });
};

// 打开抽屉
const drawerRef = ref<InstanceType<typeof WorkstationDrawer>>();
const openDrawer = (title: string, row: Partial<Workstation.WorkstationListItem> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    api: title === "新增" ? addWorkstation : title === "编辑" ? editWorkstation : undefined,
    getTableList: getTableData
  };
  drawerRef.value?.acceptParams(params);
};

// 新增工位
const addWorkstation = async (params: Workstation.CreateWorkstationRequestDto) => {
  console.log("params",params)
  return await createWorkstation(params);
};

// 编辑工位
const editWorkstation = async (params: Workstation.WorkstationListItem) => {
  return await updateWorkstation(params.id, params);
};

// 页面加载时获取数据
onMounted(() => {
  getTableData();
  loadProductionLineOptions();
});
</script>

<style scoped>
.search-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.table-header {
  margin-bottom: 16px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}
</style>